package com.example.webcourse

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.Button
import androidx.appcompat.app.AlertDialog

class UseJsActivity : AppCompatActivity() {
    private var webView: WebView? = null
    private var button: Button? = null

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_use_demo)
        webView = findViewById(R.id.webView)
        button = findViewById(R.id.button)
        webView?.settings?.run {
            javaScriptEnabled = true // 设置于js交互权限
            javaScriptCanOpenWindowsAutomatically = true // 运行js弹窗
        }
        webView?.loadUrl("file:///android_asset/javascript.html")
        button?.setOnClickListener {
            if (Build.VERSION.SDK_INT < 18) {
                webView?.loadUrl("javascript:callJS()")
            } else {
                webView?.evaluateJavascript("javascript:callJS()") {
                    // 这里接收的返回值是该函数的返回值，如果没有return就为null 还是要搭配webChromeClient
                    Log.d("kkkkkkkk", it)
                }
            }
            webView?.webChromeClient = object : WebChromeClient() {
                override fun onJsAlert(
                    view: WebView,
                    url: String?,
                    message: String,
                    result: JsResult
                ): Boolean {
                    AlertDialog.Builder(this@UseJsActivity)
                        .setTitle("Alert")
                        .setMessage(message)
                        .setPositiveButton("确认", DialogInterface.OnClickListener { _, i ->
                            result.confirm()
                        })
                        .setCancelable(false)
                        .create().show()
                    return true
                }
            }
        }
    }
}